/**
 * 购物车 
 */
//选择的优惠券
var couponData = [];

if (!Array.prototype.indexOf) {
	Array.prototype.indexOf = function(obj) {
        for (var i=0; i<this.length; i++) {
            if (this[i]==obj) {
                return i;
            }
        }
        return -1;
    }
}
//新优惠券是否可用
var CouponIsAvailable = function(sid, aid) {
	if(aid > 0) {
		var isAvailable = false;
		var uaid = $('#coupon_select_' + aid).attr('uaid');
		$("input:checked[aid]").each(function() {
			//判断是否有优惠券正在使用
			if (uaid > 0) {
				var _aid      = $(this).attr('aid');
				var _courseid = $(this).attr('courseid');
				if (aid != _aid) {
					if ($('#coupon_select_' + _aid).attr('uaid') == uaid) {
						var finalCost = parseFloat($('#real_cost_' + _aid).text());
						$('#final_cost_' + _aid).text(finalCost.toFixed(2));
						$('#coupon_select_' + _aid).attr({
							'aid':_aid, 'sid':sid, 'uaid':0, 'courseid':_courseid
						});
						$('#coupon_select_' + _aid).text('不使用优惠券');
					}
				}
			}
			if ($(this).attr('aid') == aid) {
				isAvailable = true;
			}
		});
		if (!isAvailable) {
			if (aid) {
				var finalCost = parseFloat($('#real_cost_' + aid).text());
				$('#final_cost_' + aid).text(finalCost.toFixed(2));
			}
			$.ckAlert({
				message:'优惠课程未被选择，需重新选择优惠券！'
							
			});
			var courseid = $('#coupon_select_' + aid).attr('courseid');
			$('#coupon_select_' + aid).attr({
				'aid':aid, 'sid':sid, 'uaid':0, 'courseid':courseid
							
			});
			$('#coupon_select_' + aid).text('不使用优惠券');
		}
	}
};
//统计课程数和总价格
var calculateCart = function() {
	var totalCost        = 0;//总价
	var saleCost         = 0;//优惠价
	var courseCount      = $("input:checked[aid]").length;//选中的课程总数
	var totalCourseCount = $("input:checkbox[aid]").length;//购物车课程总数
	var sidList          = [];//学校ID
	$("input:checked[aid]").each(function() {
		if ($('#final_cost_' + $(this).attr('aid')).length > 0) {
			totalCost += parseFloat($('#final_cost_'+$(this).attr('aid')).text());
		} else {
			totalCost += parseFloat($('#real_cost_'+$(this).attr('aid')).text());
		}
		//优惠价格计算
		saleCost  += parseFloat($('#real_cost_'+$(this).attr('aid')).text());

	});
	$("input[type=checkbox]").each(function() {
		if (sidList.indexOf($(this).attr('sid')) == -1) {
			sidList.push($(this).attr('sid'));
		}
	});
	if (courseCount < totalCourseCount) {
		$('#checkall1, #checkall2').attr('checked', false);
		$.each(sidList, function(i, item) {
			var state  = true,
			Teacher = 0;
			$('input[type=checkbox]').each(function() {
				sid = parseInt($(this).attr('sid'));
				if (item == sid) {
					Teacher = item;
					if ($(this).is(':checked') == false) {
						state = false;
						return false;
					}
				}
			});
			if (state) {
				$('#Teacher_checkall_' + Teacher).attr('checked', true);
			} else {
				$('#Teacher_checkall_' + Teacher).attr('checked', false);
			}
			state  = true;
			Teacher = 0;
		});
	}
	else if (courseCount == totalCourseCount) {
		$('#checkall1, #checkall2').attr('checked', true);
		$('.Teacher_checkall').attr('checked', true);
	}
	$('#course_count').text(courseCount);
	$('#total_cost').text(totalCost.toFixed(2));
	saleCost = saleCost - totalCost;
	$('#sale_cost_cnt').text(saleCost.toFixed(2));
};
//计算折扣后的课程价格
var calculateCouponCost = function(aid) {
	var realCost = parseFloat($('#real_cost_'+aid).text());
	var reduceCost = parseFloat($('#coupon_'+aid).val());
	$('#reduce_cost_'+aid).text(reduceCost.toFixed(2));
	var finalCost = realCost - reduceCost;
	if (finalCost < 0) {
		finalCost = 0.00;
	}
	$('#final_cost_'+aid).text(finalCost.toFixed(2));
	calculateCart();
};
//新计算折扣后的课程价格
var calculateCouponCostNew = function(sid, aid) {
	var courseid = $('#coupon_select_' + aid).attr('courseid');
	var uaid     = $('#coupon_select_' + aid).attr('uaid');
	var realCost = parseFloat($('#real_cost_' + aid).text());
	if (uaid > 0) {
		var reduceCost = parseFloat($('.coupon_' + courseid + '_' + uaid).text());
		var finalCost  = realCost - reduceCost;
		if (finalCost < 0) {
			finalCost = 0.00;
		}
		$('#final_cost_' + aid).text(finalCost.toFixed(2));
	} else {
		$('#final_cost_' + aid).text(realCost.toFixed(2));
	}
	$("input:checked[aid]").each(function() {
		var cartid = $(this).attr('aid');
		var _sid   = $(this).attr('sid');
//		if(_sid) {
//			var courseCost = parseFloat($('#real_cost_' + cartid).text());
//			$('#final_cost_' + cartid).text(courseCost.toFixed(2));
//		}
	});
	calculateCart();
};
//清空优惠券
var clearCouponCourse = function(sid) {
	if (sid == 0) {
		$("input:checked[aid]").each(function() {
			var cartid     = $(this).attr('aid');//购物车编号
			var courseid   = $(this).attr('courseid');//课程编号
			var _sid       = $(this).attr('sid');//学校编号
			var courseCost = parseFloat($('#real_cost_' + cartid).text());
			$('#final_cost_' + cartid).text(courseCost.toFixed(2));
			$('#coupon_select_' + cartid).attr({
				'aid':cartid, 'sid':_sid, 'uaid':0, 'courseid':courseid
							
			});
			$('#coupon_select_' + cartid).text('不使用优惠券');
		});
	} else {
		$("input:checked[sid=" + sid + "]").each(function() {
			var cartid     = $(this).attr('aid');//购物车编号
			var courseid   = $(this).attr('courseid');//课程编号
			var courseCost = parseFloat($('#real_cost_' + cartid).text());
			$('#final_cost_' + cartid).text(courseCost.toFixed(2));
			$('#coupon_select_' + cartid).attr({
				'aid':cartid, 'sid':sid, 'uaid':0, 'courseid':courseid
							
			});
			$('#coupon_select_' + cartid).text('不使用优惠券');
		});
	}
};
//购物车内容变动检查
var checkCart = function(params) {
	var ids = KK.base64_encode(params.join(",")),
	boxy = null,
	ret = true;
	$.ajax({
		url : "/?mod=order&act=create&do=checkCart",
		type : "post",
		data : "ids="+encodeURIComponent(ids),
		dataType : "json",
		async : false,
		beforeSend:function() {
			boxy = $.ckTipsBoxy({
				type:"loading", width:300, mask:true, message:"数据提交中，请稍后..."
							
			});
		}
		,
		success : function(rs) {
			boxy.cancel();
			if(rs.code < 0) {
				switch(rs.code) {
					case -250:
					$.ckAlert({
						width : 420, message : rs.data, callback : function() {
							window.location.href = KK._ucurl+"/login";
						}
					});
					break;
					case -1:
					$.ckConfirm({
						width:450,
						message:rs.data,
						ok:function() {
							window.location.href = "/course/index.html";
						}
					});
					break;
					case -2:
					$.ckConfirm({
						width : 500, message : rs.data, ok : function() {
							window.location.reload();
						}
					});
					break;
					case -3:
					$.ckAlert({
						message : rs.data
											
					});
					break;
				}
				ret = false;
			} else {
				ret = true;
			}
		}
	});
	return ret;
}

$(function() {
	$('.yhq-clk').click(function() {
		var par = $(this).parent();
        if (par.hasClass('curr')) {
            par.removeClass('curr').children('.yhq-box').stop(true).slideUp(400);
        }
        else {
            par.addClass('curr').children('.yhq-box').stop(true).slideDown(400);
        }
	}).parent().mouseleave(function() {
		$(this).children('.yhq-box').slideUp(400, function () {
            $(this).parent().removeClass('curr');
        });
	});
	//取消选中不能提交的课程
	$("input:checkbox[error=0]").attr("checked", true);
	$("input:checkbox[error=1]").attr("checked", false);
	//calculateCart();
	//全选
	$("#checkall1, #checkall2").click(function() {
		if ($(this).attr('checked')) {
			$("input:checkbox").attr("checked", true);
		} else {
			clearCouponCourse(0);
			$("input:checkbox").attr("checked", false);
		}
		calculateCart();
	});
	//选择课程
	$("input:checkbox[aid]").click(function() {
		if (!$(this).attr('checked')) {
			var sid  = $(this).attr('sid');
			var aid  = $(this).attr('aid');
			var _aid = $('#coupon_select_' + aid).attr('aid');
			CouponIsAvailable(sid, _aid);
		}
		calculateCart();
	});
	//单个删除
	$(".deleteCart").click(function() {
		var aid = $(this).attr('aid');
		$.ckConfirm({
			message:'你确定要从购物车中移除该课程吗？',
			ok:function() {
				var loading = null;
				$.ajax({
					url:'/?mod=cart&act=operate&do=remove',
					data:'ids='+aid,
					type:'post',
					dataType:'json',
					beforeSend:function() {
						loading = $.ckTipsBoxy({
							type:"loading", mask:true, message:"操作中，请稍后"
													
						});
					}
					,
					success:function(ret) {
						loading.cancel();
						if (ret.code == 0) {
							window.location.reload();
						} else {
							$.ckAlert({
								message:ret.data		
							});
						}
					}
				});
			}
		});
		return false;
	});
	//批量删除
	$(".batch_del").click(function() {
		var ids = new Array();
		$("input:checked[aid]").each(function() {
			ids.push($(this).attr('aid'));
		});
		$.ckConfirm({
			width:368,
			message:'确实要将所有选中的课程从购物车中移除吗？',
			ok:function() {
				var loading = null;
				$.ajax({
					url:'/?mod=cart&act=operate&do=remove',
					data:'ids='+ids.join(','),
					type:'post',
					dataType:'json',
					beforeSend:function() {
						loading = $.ckTipsBoxy({
							type:"loading", mask:true, message:"操作中，请稍后"
													
						});
					}
					,
					success:function(ret) {
						loading.cancel();
						if (ret.code == 0) {
							window.location.reload();
						} else {
							$.ckAlert({
								message:ret.data						
							});
						}
					}
				});
			}
		});
		return false;
	});
	//提交订单
	$("#postBtn").click(function() {
		var params = new Array();
		var warnflag = false;
		$("input:checked[aid]").each(function() {
			var cobj   = $(this);
			var cartId = cobj.attr('aid');//购物车编号
			var sid    = cobj.attr('sid');//学校编号
			if(cobj.attr('error') == '1') {
				var msg = $('#show_error_' + sid).text();
				$.ckAlert({
					message:msg+$('#trWarn_'+cartId).find('th').text()
									
				});
				$(this).removeAttr('checked');
				warnflag = true;
				calculateCart();
				return false;
			}
			//			var couponObject = $("#coupon_"+cartId);
			var couponObject = $("#coupon_select_" + cartId);
			var couponId     = 0;//优惠券使用编号
			if (couponObject.attr('uaid') > 0) {
				var _cartId   = couponObject.attr('aid');
				if (_cartId == cartId) {
					couponId = couponObject.attr('uaid');
				}
			}
			params.push(cartId + ":" + couponId);
		});
		if (warnflag) {
			return false;
		}
		if (params.length == 0) {
			$.ckAlert({
				message:"请选择要购买的课程"
							
			});
			return false;
		}
		if (checkCart(params) == false) {
			return false;
		} else {
			if (bf && cid) {
				window.location.href = "/?mod=order&act=create&ids="+KK.base64_encode(params.join(","))+"&bf="+bf+"&cid="+cid;
			} else {
				window.location.href = "/?mod=order&act=create&ids="+KK.base64_encode(params.join(","));
			}
		}
	});
	//根据学校分类选择购物车中的课程
	$('.Teacher_checkall').click(function() {
		var Teacher_call = $(this).attr('Teacher');
		if ($(this).is(':checked')) {
			$("input[sid='"+Teacher_call+"']").each(function() {
				$(this).attr('checked', true);
			});
		} else {
			//清空该学校的优惠券
			clearCouponCourse(Teacher_call);
			$("input:checked[sid='"+Teacher_call+"']").each(function() {
				$(this).attr('checked', false);
			});
		}
		//购物车重新统计合计价格和优惠
		calculateCart();
	});
	//新优惠券的选择
	$('.pack-coupon-item').click(function () {
        if (!$(this).hasClass('pack-coupon-item-done')) {
            if ($(this).hasClass('selected')) {
        		var cartId   = $(this).attr('aid');
        		var sId      = $(this).attr('sid');
        		var cId      = 0;
        		var courseId = $(this).attr('courseid');
        		var uaId     = $(this).attr('uaid');
                // 取消选中
                $(this).removeClass('selected');
                $(".pack-coupon-item[uaid='"+uaId+"']").removeClass('pack-coupon-item-done');
        		$("span[txtuaid='txt"+uaId+"']").text('使用');
                $('#coupon_select_' + cartId).text('不使用优惠券');
            }
            else {
            	var v        = '减'+$(this).find('div.price-num').text();
        		var cartId   = $(this).attr('aid');
        		var sId      = $(this).attr('sid');
        		var cId      = $(this).attr('uaid');
        		var courseId = $(this).attr('courseid');
        		$(".pack-coupon-item[uaid='"+cId+"']").addClass('pack-coupon-item-done');
        		$("span[txtuaid='txt"+cId+"']").text('被占用');
        		//判断是否对应模块中含有被占用的优惠券
        		var couponDone = $(this).parent().find('.selected');
        		if(couponDone.length > 0){
        			var uaId = couponDone.attr('uaid');
        			$(".pack-coupon-item[uaid='"+uaId+"']").removeClass('pack-coupon-item-done');
            		$("span[txtuaid='txt"+uaId+"']").text('使用');
        		}
        		$(this).siblings().removeClass('selected');
                // 选中
                $(this).removeClass('pack-coupon-item-done').addClass('selected');
                $(this).find('span.get').text('使用');
                $(this).parents('.sc-yhq').find('.nonuse-coupon').attr('checked', false);
                //$(this).parents('.sc-yhq').removeClass('nonuse');
                $(this).parents('.sc-yhq').children('.yhq-box').stop(true).slideUp(400);
                $('#coupon_select_' + cartId).text(v);
            }
            var _aid     = 0;
    		var aid      = $('#coupon_select_'+cartId).attr('aid');
    		$('#coupon_select_' + cartId).attr({
    			'aid':cartId, 'sid':sId, 'uaid':cId, 'courseid':courseId
    					
    		});	
			_aid = cartId;
			//合计价格
			calculateCouponCostNew(sId, _aid);
    		//优惠券是否可用，判断优惠券课程是否加入到购物车
    		CouponIsAvailable(sId, _aid);
    		calculateCart();
        }
    });
	//不使用优惠券
	$('.nonuse-coupon').change(function () {
        if($(this).attr('checked')) {
        	var couponDone = $(this).parents('.yhq-box').find('li.selected');
    		if(couponDone.length > 0){
    			var uaId = couponDone.attr('uaid');
    			var cartId = couponDone.attr('aid');
        		var sId      = $(this).attr('sid');
        		var cId      = 0;
        		var courseId = $(this).attr('courseid');
    			$(".pack-coupon-item[uaid='"+uaId+"']").removeClass('pack-coupon-item-done');
        		$("span[txtuaid='txt"+uaId+"']").text('使用');
        		var _aid     = 0;
        		$('#coupon_select_' + cartId).attr({
        			'aid':cartId, 'sid':sId, 'uaid':cId, 'courseid':courseId
        					
        		});	
    			_aid = cartId;
    			//合计价格
    			calculateCouponCostNew(sId, _aid);
        		//优惠券是否可用，判断优惠券课程是否加入到购物车
        		CouponIsAvailable(sId, _aid);
        		calculateCart();
    		}
            $(this).parents('.yhq-box').find('.pack-coupon-item').removeClass('selected');
            $('#coupon_select_' + cartId).text('不使用优惠券');
            $('.sc-yhq').children('.yhq-box').slideUp(400, function () {
                $('.sc-yhq').parent().removeClass('curr');
            });
        }
    });
	calculateCart();
});